package zmee.pur.src.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.botp.BFTrackerServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
* @author lijiawang
* @Date 2022/12/13 19:08
* @Description:签约操作插件
*/
public class SrcContractOperation extends AbstractOperationServicePlugIn {
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        String key = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        if ("submit".equals(key)) {
            for (int i = 0; i < dataEntities.length; i++) {
                DynamicObject contract = BusinessDataServiceHelper.loadSingle(dataEntities[i].getPkValue(), dataEntities[i].getDynamicObjectType().getName());
                //采购清单
                DynamicObjectCollection tabpurlist = contract.getDynamicObjectCollection("entryentity");
                //项目启动
                DynamicObject project = BusinessDataServiceHelper.loadSingle("src_project", "id,source", new QFilter("billno", QCP.equals, contract.getString("billno")).toArray());
                //招标立项申请单
                DynamicObject demand = BusinessDataServiceHelper.loadSingle(project.getString("source.number"), "src_demand");

                boolean checkbox = demand.getBoolean("checkbox");
                if(checkbox) {
                    String name = demand.getDataEntityType().getName();
                    Map<String, HashSet<Long>> source = BFTrackerServiceHelper.findSourceBills(name, new Long[]{demand.getLong("id")});
                    HashSet<Long> set = source.get(name);
                    for (Long id : set) {
                        DynamicObject srcDemand = BusinessDataServiceHelper.loadSingle(id, name);
                        DynamicObject pro_approval = srcDemand.getDynamicObject("pro_approval");//项目立项单
                        //招标立项申请单分录
                        DynamicObjectCollection entryentity = srcDemand.getDynamicObjectCollection("entryentity");
                        for (DynamicObject tabpur : tabpurlist) {
                        for (DynamicObject row : entryentity) {
                            //物料
                            String material = row.getString("material1.id");
                            //采购组织
                            String entryorg = row.getString("entryorg.id");
                            DynamicObject approvalbudget = row.getDynamicObject("approvalbudget");//项目预算项
                                String tabMaterial = tabpur.getString("material.id");
                                String reqorg = tabpur.getString("bidmaterial.reqorg.id");
                                if (material.equals(tabMaterial) && reqorg.equals(entryorg)) {
                                    DynamicObject approval = BusinessDataServiceHelper.loadSingle(pro_approval.getPkValue(), pro_approval.getDynamicObjectType().getName());
                                    tabpur.set("approval", approval.getDynamicObject("project"));
                                    tabpur.set("approvalid",srcDemand.getPkValue().toString());
                                    tabpur.set("approvalbudget", approvalbudget);
                                    break;
                                }
                            }
                        }
                    }
                }else{
                    DynamicObject pro_approval = demand.getDynamicObject("pro_approval");//项目立项单
                    //招标立项申请单分录
                    DynamicObjectCollection entryentity = demand.getDynamicObjectCollection("entryentity");
                    for (DynamicObject tabpur : tabpurlist) {
                        String tabMaterial = tabpur.getString("material.id");
                        String reqorg = tabpur.getString("bidmaterial.reqorg.id");
                    for (DynamicObject row : entryentity) {
                        //物料
                        String material = row.getString("material1.id");
                        //采购组织
                        String entryorg = row.getString("entryorg.id");
                        DynamicObject approvalbudget = row.getDynamicObject("approvalbudget");//项目预算项
                            if (material.equals(tabMaterial) && reqorg.equals(entryorg)) {
                                DynamicObject approval = BusinessDataServiceHelper.loadSingle(pro_approval.getPkValue(), pro_approval.getDynamicObjectType().getName());
                                tabpur.set("approval", approval.getDynamicObject("project"));
                                tabpur.set("approvalid",demand.getPkValue().toString());
                                tabpur.set("approvalbudget", approvalbudget);
                                break;
                            }
                        }
                    }
                }
                SaveServiceHelper.update(contract);
            }
        }
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        String key = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        if("audit".equals(key) || "unaudit".equals(key)){
            for (DynamicObject dataEntitie:dataEntities) {
                budgetingNum(dataEntitie,key);
            }
        }
    }

    private void budgetingNum(DynamicObject dataEntitie,String key){
        DynamicObject contract = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
        DynamicObjectCollection entr = contract.getDynamicObjectCollection("entryentity");//采购清单分录
        //签约数据
        Map<String,Map<String,String>> count=new HashMap<>();
        for (DynamicObject row:entr) {
            //签约的金额
            BigDecimal amount=new BigDecimal("0");

            DynamicObject app = row.getDynamicObject("approvalbudget");//项目预算项
            String approvalid = row.getString("approvalid");//招标立项申请单的ID
            String id=app.getPkValue().toString();
            Map<String, String> maps = new HashMap<>();
            Map<String, String> map = count.get(id + approvalid);
            if(map != null){
                amount=new BigDecimal(map.get("count"));
            }
            //招标立项申请单
            DynamicObject demand = BusinessDataServiceHelper.loadSingle(approvalid, "src_demand");
            DynamicObjectCollection entryens = demand.getDynamicObjectCollection("entryentity");
            //项目预算项
            DynamicObject budget = BusinessDataServiceHelper.loadSingle(id, "pmas_projectbudget");
            DynamicObject project = budget.getDynamicObject("project");

            //项目支出预算
            DynamicObject outbudget = BusinessDataServiceHelper.loadSingle("pmas_outbudget", "id", new QFilter[]{new QFilter("project.id", QCP.equals, project.getPkValue()).and(new QFilter("isvalid", QCP.equals,true))});
            DynamicObject pmas = BusinessDataServiceHelper.loadSingle(outbudget.getPkValue(), "pmas_outbudget");
            String group = pmas.getString("group.number");
            String parent = pmas.getString("group.parent.number");
            BigDecimal num;
            if(!"106".equals(parent)) {
                switch (group) {
                    //未税金额
                    case "10201":
                    case "10301":
                    case "10302":
                    case "10303":
                    case "10304":
                    case "10305":
                    case "10401":
                        amount = amount.add(row.getBigDecimal("amount"));
                        //招标项目立项申请单的预算合计
                        num = entyRemaining(entryens, "amount", id);
                        break;
                    //价税合计
                    default:
                        amount = amount.add(row.getBigDecimal("taxamount"));
                        num = entyRemaining(entryens, "taxamount", id);
                        break;
                }
            }else{
                amount = amount.add(row.getBigDecimal("amount"));
                //招标项目立项申请单的预算合计
                num = entyRemaining(entryens, "amount", id);
            }
            maps.put("amount",amount.toString());//签约金额
            maps.put("num",num.toString());//招标立项申请单金额
            maps.put("approvalid",approvalid);//招标立项申请单ID
            maps.put("approvalbudget",id);//项目支出预算ID
            count.put(id+approvalid,maps);

        }

        for (String id:count.keySet()) {
            Map<String, String> countMap = count.get(id);
            BigDecimal num = new BigDecimal(countMap.get("num"));
            BigDecimal amount = new BigDecimal(countMap.get("amount"));
            String approvalbudget = countMap.get("approvalbudget");
            BigDecimal tract = num.subtract(amount);//差额
            //招标立项申请单
            DynamicObject demand = BusinessDataServiceHelper.loadSingle(countMap.get("approvalid"), "src_demand");
            DynamicObject approval = demand.getDynamicObject("pro_approval");
            DynamicObject roval = BusinessDataServiceHelper.loadSingle(approval.getPkValue(), approval.getDynamicObjectType().getName());
            //项目支出预算
            DynamicObject outbudget = BusinessDataServiceHelper.loadSingle("pmas_outbudget", "id",
                    new QFilter[]{new QFilter("project.id", QCP.equals, roval.getString("project.id"))
                            .and(new QFilter("year", QCP.equals,roval.getDate("year")))
                    .and(new QFilter("isvalid", QCP.equals,true))});

            DynamicObject pmas = BusinessDataServiceHelper.loadSingle(outbudget.getPkValue(), "pmas_outbudget");
            DynamicObjectCollection treeentr = pmas.getDynamicObjectCollection("treeentryentity");
            for (DynamicObject tre:treeentr) {
                String budgetiteid = tre.getString("projectbudgetitem.id");
                if(StringUtils.equals(approvalbudget,budgetiteid)){
                    BigDecimal amoney = tre.getBigDecimal("budgetamoney");//余额
                    if(StringUtils.equals(key,"audit")) {
                        amoney = amoney.add(tract);
                    }else if( StringUtils.equals(key,"unaudit")){
                        amoney = amoney.subtract(tract);
                    }
                    tre.set("budgetamoney",amoney);
                    break;
                }
            }
            SaveServiceHelper.update(pmas);

        }


    }
    //预算金额
    private BigDecimal entyRemaining(DynamicObjectCollection entryentity,String txt,String id){
        BigDecimal num=new BigDecimal("0");
        for (DynamicObject entr:entryentity) {
            if(StringUtils.equals(entr.getString("approvalbudget.id"),id)) {
                num = num.add(entr.getBigDecimal(txt));//实际余额
            }
        }
        return  num;
    }
}
